package monster.com.cvh.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;

import java.io.File;
import java.io.FileNotFoundException;

import butterknife.BindView;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import monster.com.cvh.R;
import monster.com.cvh.application.TinkerApplicationLike;
import monster.com.cvh.fragment.base.PermissionFragment;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: 13580
 * @data: 2018/4/12
 * @function:解锁简历Fragment
 */
public class UnLockResumeFragment extends PermissionFragment implements View.OnClickListener {
    private static final String TAG = "UnLockResumeFragment";
    @BindView(R.id.webview_fragment_unlock_resume)
    WebView mWebView;
    private BaseBottomDialog mBottomDialog;
    private String mUrl;//保存WebView中的图片

    public static UnLockResumeFragment newInstance() {
        UnLockResumeFragment fragment = new UnLockResumeFragment();
        return fragment;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_unlock_resume;
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initEvent() {
        initWebView();
        mWebView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                mBottomDialog.show(getFragmentManager());
                return false;
            }
        });
        //初始化弹窗
        mBottomDialog = BottomDialog.create(getActivity().getSupportFragmentManager())
                .setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(View v) {
                        v.findViewById(R.id.tv_user_fragment_dialog_save_qr).setOnClickListener(UnLockResumeFragment.this);
                        v.findViewById(R.id.tv_user_fragment_dialog_cancel).setOnClickListener(UnLockResumeFragment.this);

                    }
                })
                .setDimAmount(0.3f)
                .setLayoutRes(R.layout.dialog_save_qr)
                .setTag("SaveQRDialog");
    }

    private void initWebView() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //网页加载完之后，java调用js方法
                view.loadUrl("javascript:saveImg()");
            }
        });
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        mWebView.addJavascriptInterface(new JsSaveImage(), "JsSaveImage");
        String url = MyConstant.RESUME_TEMPLE + "?token=" + SPUtils.getString(getActivity().getApplicationContext(), "token", "");
        mWebView.loadUrl(url);
        Log.e(TAG, "initWebView: :" + url);
    }

    /**
     * 保存图片到图库
     *
     * @param context
     * @param file
     */
    private void saveImageToGallery(Context context, File file) {
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), file.getName(), null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
    }

    /**
     * 下载图片
     */
    private void downImage() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "download" + File.separator
                + "CVLink" + File.separator;
        File appDir = new File(path);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        String fileName = "wx_cvlink.jpg";
        File file = new File(appDir, fileName);
        OkGo.<File>get(mUrl)
                .tag(this).execute(new FileCallback(file.getAbsolutePath(), file.getName()) {
            @Override
            public void onSuccess(File file, Call call, Response response) {
                saveImageToGallery(TinkerApplicationLike.getContext(), file);
                showToastShort(R.string.activity_down_and_send_resume_save_qr);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                showToastShort(R.string.activity_down_and_send_resume_save_qr_failed);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_user_fragment_dialog_save_qr:
                downImage();
                mBottomDialog.dismiss();
                break;
            case R.id.tv_user_fragment_dialog_cancel:
                mBottomDialog.dismiss();
                break;
        }
    }

    /**
     * 防止5.0webview内存泄露
     */
    @Override
    public void onDestroy() {
        OkGo.getInstance().cancelTag(this);
        if( mWebView!=null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }

            mWebView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.clearView();
            mWebView.removeAllViews();
            mWebView.destroy();

        }
        super.onDestroy();
    }

    protected final class JsSaveImage {
        private static final String TAG = "JsSaveImage";

        public JsSaveImage() {
        }

        @JavascriptInterface
        public void saveImage(final String url) {
            mUrl = url;
        }
    }
}
